<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="作者" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入作者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程搜索关键字" prop="coursePrimary">
        <el-input
          v-model="queryParams.coursePrimary"
          placeholder="请输入课程搜索关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['siyun-course:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['siyun-course:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['siyun-course:course:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="4">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
        ></el-tree>
      </el-col>
      <el-col :span="20">
        <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="课程主键" align="center" prop="id" />
          <el-table-column label="作者" align="center" prop="username" />
          <el-table-column label="课程名称" align="center" prop="courseName" />
          <el-table-column label="课程简介" align="center" prop="courseIntro" />
          <el-table-column label="备注" align="center" prop="remarks" />
          <el-table-column label="上架状态" align="center" prop="courseStatus">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.courseStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="2"
                :inactive-value="3"
                @change="handleChangeStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" prop="courseCstatus" :formatter="formatcourseCstatus"/>
          <el-table-column label="缩略图" align="center" prop="thum" width="100">
            <template slot-scope="scope">
              <image-preview :src="scope.row.thum" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
                v-hasPermi="['siyun:course:list']"
              >查看</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['siyun:course:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['siyun:course:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="作者" prop="username">
          <el-autocomplete
            v-model="form.username"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入作者"
            @select="handleAutocompleteSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入课程名称" :readonly="isViewing"/>
        </el-form-item>
        <el-form-item label="课程简介">
          <editor v-model="form.courseIntro" :min-height="192" :disabled="isViewing"/>
        </el-form-item>
        <el-form-item label="备注">
          <editor v-model="form.remarks" :min-height="192" :disabled="isViewing"/>
        </el-form-item>
        <el-form-item label="课程价格" prop="courseNprice">
          <el-input v-model="form.courseNprice" placeholder="请输入课程现价" :readonly="isViewing"/>
        </el-form-item>
        <el-form-item label="课程分类" prop="classify">
          <el-input v-model="form.classify" placeholder="请输入课程分类" :readonly="isViewing"/>
        </el-form-item>
        <el-form-item label="课程搜索关键字" prop="coursePrimary">
          <el-select v-model="value1" multiple placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缩略图" prop="thum">
          <image-upload v-model="form.thum" :disabled="isViewing"/>
        </el-form-item>
        <el-form-item label="课程视频" prop="imgUrls">
          <el-input v-model="form.imgUrls" placeholder="请输入课程视频" :readonly="isViewing"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isViewing" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看课程对话框 -->
    <el-dialog :title="title" :visible.sync="viewOpen" width="1000px" append-to-body custom-class="view-dialog">
      <el-descriptions class="margin-top" :column="3" :size="size" border>
        <!-- Top Section -->
        <el-descriptions-item label="作者">{{ form.username }}</el-descriptions-item>
        <el-descriptions-item label="课程名称">{{ form.courseName }}</el-descriptions-item>
        <el-descriptions-item label="课程视频">{{ form.imgUrls }}</el-descriptions-item>
        <el-descriptions-item label="缩略图">
          <image-preview :src="form.thum" :width="200" :height="200"/>
        </el-descriptions-item>
        <el-descriptions-item label="课程简介">{{ form.courseIntro }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ form.remarks }}</el-descriptions-item>
        <el-descriptions-item label="课程原价">{{ form.coursePrice }}</el-descriptions-item>
        <el-descriptions-item label="课程现价">{{ form.courseNprice }}</el-descriptions-item>
        <el-descriptions-item label="课程搜索关键字">
          <el-tag v-for="tag in form.coursePrimary" :key="tag" style="margin-right: 5px;">{{ tag }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <br />
      <el-descriptions class="margin-top" :column="2" :size="size" border>
        <!-- Middle Section -->
        <el-descriptions-item label="点赞数量">{{ form.likeNum }}</el-descriptions-item>
        <el-descriptions-item label="分享数量">{{ form.shareNum }}</el-descriptions-item>
        <el-descriptions-item label="收藏数量">{{ form.collectNum }}</el-descriptions-item>
        <el-descriptions-item label="预览数量">{{ form.lookNum }}</el-descriptions-item>
        <el-descriptions-item label="销售数量">{{ form.saleNum }}</el-descriptions-item>
      </el-descriptions>
      <br />
        <!-- Bottom Section -->
      <el-descriptions class="margin-top" :column="2" :size="size" border>
        <el-descriptions-item label="创建人">{{ form.createBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ form.createTime }}</el-descriptions-item>
        <el-descriptions-item label="修改人">{{ form.updateBy }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ form.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewClose">关 闭</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { listCourse, getCourse, delCourse, addCourse, updateCourse, courseCategoryTree} from "@/api/siyun/course";

export default {
  name: "Course",
  data() {
    return {
      // 树形数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableData: [],
      classify: '',

      size: 'medium',
      viewOpen: false, // 控制查看对话框的显示与隐藏
      // 关键字
      options: [{
          value: '选项1',
          label: 'JAVA'
        }, {
          value: '选项2',
          label: 'MYSQL'
        }, {
          value: '选项3',
          label: 'C++'
        }, {
          value: '选项4',
          label: 'C语言'
        }, {
          value: '选项5',
          label: '素质教育'
      }],
      value1:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为查看模式
      isViewing: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        courseName: null,
        coursePrimary: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "作者不能为空", trigger: "blur" }
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        coursePrice: [
          { required: true, message: "课程原价不能为空", trigger: "blur" }
        ],
        courseNprice: [
          { required: true, message: "课程现价不能为空", trigger: "blur" }
        ]
      },
      // 自动完成建议列表
      restaurants: []
    };
  },
  created() {
    this.getList();
    this.getCourseCategoryTree();
  },
  mounted() {
    this.restaurants = this.loadAll();
  },
  methods: {
    //树形数据条件查询
    handleNodeClick(data){
      console.log(data);
      this.queryParams.classify = data.id;
      this.handleQuery();
    },
    //树形数据显示
    getCourseCategoryTree() {
          courseCategoryTree().then(response => {
            this.treeData = response.data; // 假设response.data是树形数据
          }).catch(error => {
            console.error('获取课程分类树失败', error);
          });
    },
    //关闭查看窗口
    viewClose() {
        this.viewOpen = false;
        this.reset();
    },
    // 远程查询
    loadAll() {
      return [
        { "value": "theguo", "address": "长宁区新渔路144号" },
        { "value": "CX330", "address": "上海市长宁区淞虹路661号" },
      ];
    },
    querySearchAsync(queryString, cb) {
      let restaurants = this.restaurants;
      let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleAutocompleteSelect(item) {
      console.log(item);
    },
    formatcourseCstatus(row) {
      const statusMap = {
        2: '已审核',
        3: '未审核',
        4: '审核中',
        5: '审核失败',
        6: '其他',
      };
      return statusMap[row.courseCstatus] || '未知';
    },
    handleChangeStatus(row) {
        const newStatus = row.courseStatus === 2 ? 2 : 3;
        updateCourse({ id: row.id, courseStatus: newStatus })
          .then(response => {
            this.msgSuccess("状态更新成功");
            this.getList(); // 刷新列表以反映最新状态
          })
          .catch(error => {
            this.msgError("状态更新失败");
            row.courseStatus = row.courseStatus === 2 ? 3 : 2; // 回滚状态
          });
      },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {
        console.log(response)
        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.isViewing = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加课程";
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const courseId = row.id || this.ids[0];
      getCourse(courseId).then(response => {
        this.form = response.data;
        this.title = "修改课程";
        this.open = true;
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const courseId = row.id;
      getCourse(courseId).then(response => {
        this.form = response.data;
        this.title = "查看课程";
        this.viewOpen = true; // 打开查看对话框
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCourse(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourse(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.id || this.ids;
      this.$confirm('是否确认删除课程编号为"' + courseIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delCourse(courseIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/course/export', {
        ...this.queryParams
      }, `course_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.view-dialog .el-form-item {
  margin-bottom: 15px;
}

.view-dialog .el-form-item__label {
  font-weight: bold;
}

.view-dialog .el-tag {
  margin-top: 5px;
}

.view-dialog .el-row:not(:last-child) {
  margin-bottom: 20px;
}
</style>
